<template>
  <div id="app">
    <div id="admin">
      <div class="pos" v-loading="loading">
        <h1 class="adminh1">用户登录</h1>
        <el-form :model="ruleForm" :rules="rules" ref="loginFrom" label-width="100px">
          <el-form-item label="用户名：" prop="username">
            <el-input style="width: 250px" type="text" v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密 码：" prop="password">
            <el-input style="width: 250px" type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleForm)">登入</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/useAuthStore'
import { useRouter } from 'vue-router'
import { login } from '@/plugins/login'
const router = useRouter()

let ruleForm = reactive({
  username: '',
  password: ''
})

let rules = reactive({
  username: [
    { required: true, message: '用户名必填' },
    { pattern: /^[a-zA-Z0-9_]{4,16}$/, min: 4, max: 18, message: '请输入正确的用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码必填' },
    { min: 6, max: 16, message: '请输入正确的密码格式', trigger: 'blur' }
  ]
})

let loading = ref(false)

const useAuthStoreData = useAuthStore()

// 提交函数
function submitForm(from) {
  login(from.username, from.password).then(
    data => {
      if (data.code === 200) {
        let user = useAuthStoreData.getUser
        user.tokenHead = data.data.tokenHead
        user.token = data.data.token
        useAuthStoreData.setAuth(true)
        useAuthStoreData.setUser(user)
        localStorage.setItem('tokenHead', user.tokenHead)
        localStorage.setItem('token', user.token)
        ElMessage({
          showClose: true,
          message: '登入成功',
          type: 'success'
        })
        router.push('/dashboard')
      } else {
        ElMessage({
          showClose: true,
          message: data.message,
          type: 'error'
        })
      }
    },
    error => {
      console.log('错误', error.message)
    }
  )
}
</script>

<style>
* {
  padding: 0;
  margin: 0;
}

#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}
#admin {
  position: absolute;
  top: 40%;
  left: 50%;
  margin-top: -200px;
  margin-left: -250px;
  width: 500px;
  height: 400px;
  background: #fff;
  border-radius: 10%;
  box-shadow: 8px 10px 10px rgb(177, 223, 242);
}
.adminh1 {
  margin: 20px 0;
  text-shadow: 10px 13px 3px rgb(207, 207, 207);
  text-align: center;
}
.pos {
  width: 450px;
  height: 350px;
  position: absolute;
  top: 25px;
  left: 25px;
}
</style>
